#include<bits/stdc++.h>
using namespace std;
typedef vector<vector<int> > matrix;
mt19937 g(time(0));
inline void chadd(int &x,int y,int m){
  if((x+=y)>=m)x-=m;
}
inline matrix mul(matrix a,matrix b,int m){
  matrix c(a.size(),vector<int>(b[0].size()));
  for(int i=0;i<a[0].size();i++)
    for(int j=0;j<a.size();j++)
      for(int k=0;k<b[0].size();k++)
        chadd(c[j][k],1ll*a[j][i]*b[i][k]%m,m);
  return c;
}
int main(){
  freopen("matrix.in","r",stdin);
  freopen("matrix.out","w",stdout);
  ios::sync_with_stdio(false);
  cin.tie(0); cout.tie(0);
  int t; cin>>t;
  while(t--){
    int m,n; cin>>m>>n;
    matrix a(n,vector<int>(n)),b=a,c=a,v(1,vector<int>(n));
    for(auto &i:a)for(auto &j:i)cin>>j;
    for(auto &i:b)for(auto &j:i)cin>>j;
    for(auto &i:c)for(auto &j:i)cin>>j;
    for(auto &i:v)for(auto &j:i)j=g()%m;
    cout<<(mul(mul(v,a,m),b,m)==mul(v,c,m)?"Yes\n":"No\n");
  }
  return 0;
}